package edu.example;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.sql.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;


public class MainScreenFrame extends JFrame
{
	//Int that track the number of incomplete reviews
	private int incomNum;
	
	//Declare GUI component
	private JLabel incompleteImgLabel;
	private JLabel incomplete;
	
	private JLabel bannerLabel;
	
	private JLabel uploadLabel;
	private JButton uploadButton;
	
	private JLabel viewTabelLabel;
	private JButton vewTableButton;
	
	private JLabel viewAppLabel;
	private JButton viewAppButton;
	
	private JLabel createReviewLabel;
	private JButton createReviewButton;
	
	private JLabel resetLabel;
	private JButton resetButton;
	
	private JLabel settingLabel;
	private JButton settingButton;
	
	private JButton logoutButton;
	
	private JPanel bannerPanel;
	private JPanel incompletePanel;
	private JPanel mainPanel;	
	private JPanel logoutPanel;
	
	//Declare handlers
	private SettingHandler settingHandler;
	private LogoutHandler logoutHandler;
	private UploadAppHandler uploadAppHandler;
	private ViewTableHandler viewTableHandler;
	private ViewAppHandler viewAppHandler;
	private CreateReviewAssgnHandler createReviewAssgnHandler;
	private ResetAppHandler resetAppHandler;
	private WindowClosingHandler windowClosingHandler;
	
	private ApplicationManagerCloud formatter;
	private UserManager um;
	private ReviewManager rm;
	
	/**
	 * Constructor
	 */
	public MainScreenFrame(UserManager initUm)
	{
		this.setTitle("Graduate Application Review System ");
		this.setSize(1280, 720);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		um = initUm;
		initData();
		layoutGUI();
	}
	
	public void initData()
	{
		//File file1 = new File("AY.txt");
		File file2 = new File("AY-map.txt");
		//File file3 = new File("OTS.txt");
		File file4 = new File("OTS-map.txt");
		rm = new ReviewManager(um);
		formatter = new ApplicationManagerCloud(null, null, file2, null, file4);
	}
	
	public void layoutGUI()
	{
		// size and locate the dialog at the center of the screen
		int w = getWidth();
		int h = getHeight();
		Toolkit tk = Toolkit.getDefaultToolkit();
		Dimension screenSize = tk.getScreenSize();
		int screenWidth = screenSize.width;
		int screenHeight = screenSize.height;
		int x = (screenWidth - w)/2;
		int y = (screenHeight - h)/2;
		setLocation(x,y);
		
		//Construct GUI components
		bannerLabel = new JLabel();
		bannerLabel.setIcon(new ImageIcon("logohome.png"));
		
		incompleteImgLabel = new JLabel();
		incompleteImgLabel.setIcon(new ImageIcon("incomplete.png"));
		incomNum = um.getCurrentUser().getNumAssignedReviews() - um.getCurrentUser().getCompletedReview();
		incomplete = new JLabel(incomNum+" Incomplete Reviews");
		incomplete.setPreferredSize(new Dimension(160, 32));
		
		uploadLabel = new JLabel();
		uploadLabel.setIcon(new ImageIcon("upload.png"));
		uploadButton = new JButton("Upload Applications");
		uploadButton.setPreferredSize(new Dimension(250, 64));
		if (!um.isChair())
			uploadButton.setEnabled(false);
		
		viewTabelLabel = new JLabel();
		viewTabelLabel.setIcon(new ImageIcon("table.png"));
		vewTableButton = new JButton("View Table of Application");
		vewTableButton.setPreferredSize(new Dimension(250, 64));
		
		viewAppLabel = new JLabel();
		viewAppLabel.setIcon(new ImageIcon("app.png"));
		viewAppButton = new JButton("View/Edit Application");
		viewAppButton.setPreferredSize(new Dimension(250, 64));
		
		createReviewLabel = new JLabel();
		createReviewLabel.setIcon(new ImageIcon("review.png"));
		createReviewButton = new JButton("Create Reivew Assignment");
		createReviewButton.setPreferredSize(new Dimension(250, 64));
		if (!um.isChair())
			createReviewButton.setEnabled(false);

		resetLabel = new JLabel();
		resetLabel.setIcon(new ImageIcon("reset.png"));
		resetButton = new JButton("Reset Number of Assigned Reviews");
		resetButton.setPreferredSize(new Dimension(250, 64));
		if (!um.isChair())
			resetButton.setEnabled(false);
		
		settingLabel = new JLabel();
		settingLabel.setIcon(new ImageIcon("setting.png"));
		settingButton = new JButton("Settings");
		settingButton.setPreferredSize(new Dimension(250, 64));

		if (um.isChair())
			settingButton.setEnabled(true);
		else settingButton.setEnabled(false);

		
		logoutButton = new JButton("Logout");
		logoutButton.setPreferredSize(new Dimension(150, 50));
		
		incompletePanel = new JPanel();
		mainPanel = new JPanel();
		logoutPanel = new JPanel();
		bannerPanel = new JPanel();
		
		//Setup layout
		GridBagLayout gbl = new GridBagLayout();
		mainPanel.setLayout(gbl);
		mainPanel.setBackground(Color.white);
		
		addJComponentToContainerUsingGBL(uploadLabel, 			mainPanel,	0,	0,	1,	1);
		addJComponentToContainerUsingGBL(uploadButton, 			mainPanel,	1,	0,	1,	1);
		addJComponentToContainerUsingGBL(viewTabelLabel, 		mainPanel,	0,	1,	1,	1);
		addJComponentToContainerUsingGBL(vewTableButton, 		mainPanel,	1,	1,	1,	1);
		addJComponentToContainerUsingGBL(viewAppLabel, 			mainPanel,	0,	2,	1,	1);
		addJComponentToContainerUsingGBL(viewAppButton, 		mainPanel,	1,	2,	1,	1);
		addJComponentToContainerUsingGBL(createReviewLabel, 	mainPanel,	0,	3,	1,	1);
		addJComponentToContainerUsingGBL(createReviewButton, 	mainPanel,	1,	3,	1,	1);
		addJComponentToContainerUsingGBL(resetLabel, 			mainPanel,	0,	4,	1,	1);
		addJComponentToContainerUsingGBL(resetButton, 			mainPanel,	1,	4,	1,	1);
		addJComponentToContainerUsingGBL(settingLabel, 			mainPanel,	0,	5,	1,	1);
		addJComponentToContainerUsingGBL(settingButton, 		mainPanel,	1,	5,	1,	1);
		
		incompletePanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		incompletePanel.add(incompleteImgLabel);
		incompletePanel.add(incomplete);
		
		bannerPanel.setLayout(new BorderLayout());
		bannerPanel.add(bannerLabel, BorderLayout.NORTH);
		bannerPanel.add(incompletePanel, BorderLayout.SOUTH);
		
		logoutPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		logoutPanel.add(logoutButton);
		
		this.add(bannerPanel, BorderLayout.NORTH);
		this.add(mainPanel, BorderLayout.WEST);
		this.add(logoutPanel, BorderLayout.SOUTH);
		
		Container con = this.getContentPane();
		con.setBackground(Color.white);
		bannerPanel.setBackground(Color.white);
		logoutPanel.setBackground(Color.white);
		mainPanel.setBackground(Color.white);
		incompletePanel.setBackground(Color.white);
		
		//Construct handler
		settingHandler = new SettingHandler();
		logoutHandler = new LogoutHandler();
		uploadAppHandler = new UploadAppHandler();
		viewTableHandler = new ViewTableHandler();
		viewAppHandler = new ViewAppHandler();
		createReviewAssgnHandler = new CreateReviewAssgnHandler();
		resetAppHandler = new ResetAppHandler();
		windowClosingHandler = new WindowClosingHandler();
		
		//Link component to hander
		uploadButton.addActionListener(uploadAppHandler);
		settingButton.addActionListener(settingHandler);
		logoutButton.addActionListener(logoutHandler);
		vewTableButton.addActionListener(viewTableHandler);
		viewAppButton.addActionListener(viewAppHandler);
		createReviewButton.addActionListener(createReviewAssgnHandler);
		resetButton.addActionListener(resetAppHandler);
		this.addWindowListener(windowClosingHandler);
	}
	
	/**
	 * GridBadLayout helper method
	 */
	public void addJComponentToContainerUsingGBL(	JComponent jc,
			Container c,
			int x,
			int y,
			int w,
			int h)
	{
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.gridx = x;
		gbc.gridy = y;
		gbc.gridwidth = w;
		gbc.gridheight = h;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.insets = new Insets(5, 5, 10, 5);
		c.add(jc, gbc);
	}
	
	class UploadAppHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent ae)
		{
			UploadAppDialog frame = new UploadAppDialog();
			frame.setVisible(true);
		}
	}
	
	class SettingHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent ae)
		{
			SettingFrame frame = new SettingFrame(MainScreenFrame.this,um);
			frame.setVisible(true);
			MainScreenFrame.this.setVisible(false);
		}
	}
	
	class ViewTableHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent ae)
		{
			selectFieldsInViewTable temp = new selectFieldsInViewTable(formatter, um);
			temp.setVisible(true);
		}
	}
	class ViewAppHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent ae)
		{
			ApplicationManagerCloud ap = ApplicationManagerCloud.getAppManager();
			SelectStudentFrame tmp = new SelectStudentFrame(um, ap.getAllApps());
			tmp.setVisible(true);
		}
	}
	
	class ResetAppHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent ae)
		{
			try{
			    Connection conn;
				conn = ConnectionUtils.getConnection();				
			    Statement statement = conn.createStatement();
			    String sql = "drop * from reviews";
			    ResultSet rs = statement.executeQuery(sql);
			}catch(SQLException e) {
	            e.printStackTrace();
	           } catch(Exception e) {
	               e.printStackTrace();
	              } 
			
			
		}
	}
	
	class WindowClosingHandler extends WindowAdapter
	{
		public void windowClosing(WindowEvent arg0) 
		{
			//Write back EVERYTHING
			ApplicationManagerCloud ap = ApplicationManagerCloud.getAppManager();
			
			Collection<Application> temp = ap.getAllApps().values();
			Iterator<Application> it = temp.iterator();
				
			while(it.hasNext())
			{
				Application tempApp = it.next();
				Collection<String> tempV = tempApp.getData().values();
				Collection<String> tempK = tempApp.getData().keySet();
				Iterator<String> itK = tempK.iterator();
				Iterator<String> itV = tempV.iterator();
					
				while(itK.hasNext())
				{
					String tempKey = itK.next();
					String tempValue = itV.next();
					
					//Here is the key and value, WRITE IT BACK TO DATABASE
					System.out.println(tempKey+" "+tempValue);
				}
			}
			
			
			Collection<OfficialTestScore> tempS = ap.getAllScore().values();
			Iterator<OfficialTestScore> itS = tempS.iterator();
				
			while(itS.hasNext())
			{
				OfficialTestScore tempScore = itS.next();
				Collection<String> tempV = tempScore.getData().values();
				Collection<String> tempK = tempScore.getData().keySet();
				Iterator<String> itK = tempK.iterator();
				Iterator<String> itV = tempV.iterator();
				
				while(itK.hasNext())
				{
					String tempKey = itK.next();
					String tempValue = itV.next();
					
					//Here is the key and value, WRITE IT BACK TO DATABASE
					//System.out.println(tempKey+" "+tempValue);
				}
			}
			
			System.exit(0);
		}
	}
	
	class LogoutHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent ae)
		{
			//Write back EVERYTHING
			ApplicationManagerCloud ap = ApplicationManagerCloud.getAppManager();
			
			Collection<Application> temp = ap.getAllApps().values();
			Iterator<Application> it = temp.iterator();
				
			while(it.hasNext())
			{
				Application tempApp = it.next();
				Collection<String> tempV = tempApp.getData().values();
				Collection<String> tempK = tempApp.getData().keySet();
				Iterator<String> itK = tempK.iterator();
				Iterator<String> itV = tempV.iterator();
					
				while(itK.hasNext())
				{
					String tempKey = itK.next();
					String tempValue = itV.next();
					
					//Here is the key and value, WRITE IT BACK TO DATABASE
					//System.out.println(tempKey+" "+tempValue);
				}
			}
			
			
			Collection<OfficialTestScore> tempS = ap.getAllScore().values();
			Iterator<OfficialTestScore> itS = tempS.iterator();
				
			while(itS.hasNext())
			{
				OfficialTestScore tempScore = itS.next();
				Collection<String> tempV = tempScore.getData().values();
				Collection<String> tempK = tempScore.getData().keySet();
				Iterator<String> itK = tempK.iterator();
				Iterator<String> itV = tempV.iterator();
				
				while(itK.hasNext())
				{
					String tempKey = itK.next();
					String tempValue = itV.next();
					
					//Here is the key and value, WRITE IT BACK TO DATABASE
					//System.out.println(tempKey+" "+tempValue);
				}
			}
			
			rm= new ReviewManager(um);
			rm.saveToDB();
			
			formatter = formatter.getAppManager(); 
			formatter.updateSettingData();
			
			LoginInfoFrame frame = new LoginInfoFrame();
			frame.setVisible(true);
			MainScreenFrame.this.setVisible(false);
		}
	}
	
	class CreateReviewAssgnHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent ae)
		{
			CreateReviewFrame frame = new CreateReviewFrame(um, MainScreenFrame.this);
			frame.setVisible(true);
		}
	}
	
	public void updateIncompleteNum(){
		incomNum = um.getCurrentUser().getNumAssignedReviews() - um.getCurrentUser().getCompletedReview();
		incomplete.setText(incomNum+" Incomplete Reviews");
		incomplete.repaint();
	}
	
	public static void main(String[] args)
	{
		UserManager um = new UserManager();
		um.login("chair", "abc");
		MainScreenFrame frame = new MainScreenFrame(um);
		frame.setVisible(true);
	}
}
